package org.sam.swing.utils;

import java.awt.Component;
import java.awt.Container;

import javax.swing.JComponent;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.JTabbedPane;

/**
 * swing 控件助手
 * 
 * @author sam
 *
 */
public class ComponentUtil {

	/**
	 * 根据控件名称获取控件对象
	 * 
	 * @param components
	 * @param id
	 * @return
	 */
	public static JComponent findViewById(Component[] components, String id) {

		for (Component c : components) {

			if (id.equals(c.getName())) {
				return (JComponent) c;
			} else if (c instanceof JRootPane) {

				Component[] cs = ((JRootPane) c).getComponents();
				if (cs == null || cs.length <= 0)
					continue;

				JComponent find = findViewById(cs, id);
				if (find == null)
					continue;
				else
					return find;

			} else if (c instanceof JTabbedPane) {
				Component[] cs = ((JTabbedPane) c).getComponents();
				if (cs == null || cs.length <= 0)
					continue;

				JComponent find = findViewById(cs, id);
				if (find == null)
					continue;
				else
					return find;
			} else if (c instanceof JPanel) {
				Component[] cs = ((JPanel) c).getComponents();
				if (cs == null || cs.length <= 0)
					continue;

				JComponent find = findViewById(cs, id);
				if (find == null)
					continue;
				else
					return find;
			} else if (c instanceof JLayeredPane) {
				Component[] cs = ((JLayeredPane) c).getComponents();
				if (cs == null || cs.length <= 0)
					continue;

				JComponent find = findViewById(cs, id);
				if (find == null)
					continue;
				else
					return find;
			}
		}
		return null;
	}
	
	/**
	 * 查找符合条件的父容器类型
	 * @param component 当前控件
	 * @param cls 父容器类型
	 * @return 没找到或者出错，返回null
	 */
	@SuppressWarnings("unchecked")
	public static <C extends Component> C getParent(JComponent component , Class<C> cls){
		if (component == null || cls == null)
			return null;
		
		Container parent = component.getParent();
		while(parent != null){
			if (cls.isAssignableFrom(parent.getClass()))
				return (C)parent;
			
			parent = parent.getParent();
		}
		
		return null;
	}
}
